package com.kilograms.lensflareit;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class LensflareItMainActivity extends Activity implements OnClickListener {
	
	private static String TAG = "com.kilograms.lensflareit";
	
	// ids used when calling startActivityForResult
	private static final int IMAGE_PICK = 1;		// When using the gallery to pick an existing image 
	private static final int IMAGE_FROM_CAMERA = 2; // When using the camera to take a new picture
	
	private Button newBtn;
	private Button existingBtn;
	
	private File imageDirectory; // Temporary storage folder
	private String imagePath;    // Path to temporary stored image
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		// Get our Views
		newBtn = (Button) findViewById(R.id.newBtn);
		existingBtn = (Button) findViewById(R.id.existingBtn);
		newBtn.setOnClickListener(this);
		existingBtn.setOnClickListener(this);
		
		// Get and create the imageDirectory temporary storage if it does not yet exist
		// The path will typically be /mnt/sdcard/tmp, i.e. a subfolder on the root of the sd card
		imageDirectory = new File(Environment.getExternalStorageDirectory() + "/tmp/");
		if(!imageDirectory.exists()){
			Log.v(TAG, "Image directory doesn't exist. Trying to create it...");
			if(imageDirectory.mkdir()) {
				Log.v(TAG, "image directory successfully created.");
			} else {
				Log.v(TAG, "Could not create image directory");
			}
		}
		Log.v(TAG, "imageDirectory: " + imageDirectory.getPath());
	}
	
	public void onClick(View v) {
		if(v==newBtn){				// Create intent to get image from camera
			Log.v(TAG, "newBtn clicked");
			if(imageDirectory.exists()) {
				openCameraActiviry();
			} else {
				Log.v(TAG, "Image directory doesn't exist so we cannot use the camera");
			}
		} else if(v==existingBtn) {	// Start image picker intent for result (default gallery app)
			openGalleryImagePickerActivity();
		}
	}
	
	private void openCameraActiviry() {
		Log.v(TAG, "Image directory exists. Creating intent to get image from camera");
		Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
		File file = new File(imageDirectory, "temppic.png");
		Log.v(TAG, "tempFilePath: " + file.getPath());
		imagePath = file.getPath();
		i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		Log.v(TAG, "Opening camera...");
		startActivityForResult(i, IMAGE_FROM_CAMERA);
	}
	
	private void openGalleryImagePickerActivity() {
		Log.v(TAG, "existingBtn clicked. Opening image picker...");			
		Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, IMAGE_PICK);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.v(TAG, "Main: onActivityResult()");
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode==IMAGE_PICK) { // Got an image from the gallery
			if(resultCode==RESULT_OK) {
				Log.v(TAG, "Got image from gallery (image picker)");
				Uri selectedImage = data.getData();
				String[] filePathColumn = {MediaStore.Images.Media.DATA};
				
				Cursor c = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
				c.moveToFirst();
				
				int colIndex = c.getColumnIndex(filePathColumn[0]);
				String filePath = c.getString(colIndex);
				c.close();
				
				openImageEditor(filePath);
			}
		} else if(requestCode==IMAGE_FROM_CAMERA) { // Got an image from the camera activity
			if(resultCode==RESULT_OK) {
				if(imagePath != null) {
					Log.v(TAG, "Got activity result from camera");
					openImageEditor(imagePath);
				}
			}
		}
	}
	
	/**
	 * Opens our ImageEditor, passing the path of the temporary stored image (in /tmp folder of sdcard)
	 * @param filePath
	 */
	private void openImageEditor(String filePath) {
		Log.v(TAG, "Opening image editor");
//		Intent i = new Intent(this, ImageEditor.class);
		Intent i = new Intent(this, NewImageEditor.class);
		i.putExtra("filePath", filePath);
		startActivity(i);		
	}
}